package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Category;
import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

/**
 * @author suiyu_yang
 * @description 商品的Dao
 * @date 2019-06-09 17:53
 * @email suiyu_yang@163.com
 */
public class GoodsDao {
    public void insert(Goods goods) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(goods);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(Goods goods) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(goods);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void update(Goods goods) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(goods);

        session.flush();
        transaction.commit();
        HibernateUtil.closeSession();
    }

    public List<Goods> getGoodsByName(String goodsName) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Goods goods where goods.goodsName like '%" + goodsName + "%' ";

        List<Goods> goods = session.createQuery(sql).list();

        HibernateUtil.closeSession();
        return goods;
    }

    public List<Goods> getAllGoods() {
        Session session = HibernateUtil.currentSession();

        String sql = "from Goods goods";

        List<Goods> goodsList = session.createQuery(sql).list();

        HibernateUtil.closeSession();

        return goodsList;
    }

    public Goods getGoodsById(int id) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Goods goods where goods.id = '" + id + "' ";

        Goods goods = (Goods) session.createQuery(sql).uniqueResult();
        HibernateUtil.closeSession();
        return goods;
    }

}
